package com.aluka.nirvana.framework.wechat.mina.api;

import com.aluka.nirvana.framework.wechat.mina.constant.MinaCommonConstant;
import com.aluka.nirvana.framework.wechat.mina.model.MinaBasicRequest;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * 微信小程序API接口基类
 * 用于处理一些冗余逻辑
 * @author gongli
 * @since 2020/4/7 19:05
 */
public abstract class BasicManaApi {

    /**
     * 向GET请求地址拼接目标参数
     * @param url GET请求地址
     * @param requestSource 目标参数 extends : com.aluka.nirvana.framework.wechat.mina.model.MinaBasicRequest
     * @return 填充后的GET请求地址
     */
    public String appendParametersForGetRequestUrl(String url , MinaBasicRequest requestSource){
        //url eg: https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={js_code}&grant_type={grant_type}
        Assert.notNull(requestSource,String.format("%s.%s:接口请求对象不能为空!",
                this.getClass(),Thread.currentThread().getStackTrace()[1].getMethodName()));

        Map<String, Object> parametersMap = requestSource.covertMap();

        Assert.notEmpty(parametersMap,String.format("%s.%s:接口参数内容不能为空!",
                this.getClass(),Thread.currentThread().getStackTrace()[1].getMethodName()));

        return appendParameters(url,parametersMap);
    }


    private String appendParameters(String url,Map<String, Object> parametersMap){
        StringBuilder urlAppender = new StringBuilder(url);

        urlAppender.append(MinaCommonConstant.QUESTION_MARK);

        parametersMap.forEach((fieldName,fieldValue) ->
                urlAppender.append(fieldName)
                    .append(MinaCommonConstant.EQUALS_MARK)
                    .append(fieldValue)
                    .append(MinaCommonConstant.AND_MARK));

        return urlAppender.delete(urlAppender.length() - 1, urlAppender.length()).toString();
    }
}
